// pages/orders/index/index.js
const app = getApp()
Page({
  data: {
    orderDetails: [], // 用于存储订单详情
    orderId: null,    // 存储订单ID
    imgUrl: '',
    user:{}
  },
  onPullDownRefresh(){
    this.onLoad()
},
  onLoad: function (options) {
    this.getAdress()
    console.log(options)
    const orderId = options.orderId;
    this.setData({ orderId });

    if (orderId) {
      this.fetchOrderDetails(orderId);
    }
    this.setData({
      imgUrl: app.imgUrl
    })
    wx.stopPullDownRefresh()
  },
  handlePay() {
    const token = wx.getStorageSync('token');
    wx.request({
      url: app.apiUrl + '/orders/buyes/' + this.data.orderId,
      method: "POST",
      header: {
        "token": token
      },
      data: {

      },
      success: res => {
        if (res.data.code === 1) {
          wx.showToast({
            title: '支付成功',
            icon: 'success',
            success: () => {
              wx.switchTab({
                url: '/pages/index/index',
              });
            }
          });
          // 重新获取购物车列表
        } else {
          wx.showToast({
            title: res.data.msg,
            icon: 'error',
          });
        }
      }
    })
  },

  fetchOrderDetails: function (orderId) {
    wx.request({
      url: app.apiUrl + '/orderItems/list?orderIds=' + orderId,
      method: 'GET',
      success: (res) => {
        if (res.data.code === 1) {
          this.setData({
            orderDetails: res.data.data,
          });
        } else {
          wx.showToast({
            title: '获取订单详情失败',
            icon: 'none',
          });
        }
      },
      fail: () => {
        wx.showToast({
          title: '请求失败，请稍后重试',
          icon: 'none',
        });
      }
    });
  },
  getAdress(){
    const token = wx.getStorageSync('token');
    wx.request({
      url: app.apiUrl + '/users/address',
      method: "GET",
      header: {
        "token": token
      },
      success: res => {
        console.log(res)
        if (res.data.code === 1) {
          this.setData({
            user:res.data.data
          })
        }
      }
    })
  },


  handleCancel: function () {
    // 处理取消订单逻辑
    const token = wx.getStorageSync('token');
    wx.request({
      url: app.apiUrl + '/orders/cancel/' + this.data.orderId,
      method: "POST",
      header: {
        "token": token
      },
      data: {

      },
      success: res => {
        if (res.data.code === 1) {
          wx.showToast({
            title: '取消订单成功',
            icon: 'success',
            success: () => {
              wx.switchTab({
                url: '/pages/index/index',
              });
            }
          });
          // 重新获取购物车列表
        } else {
          wx.showToast({
            title: res.data.msg,
            icon: 'error',
          });
        }
      }
    })
  },
});
